package com.workflow.service.impl;

import java.util.Date;
import java.util.List;

import com.common.util.AbstractManager;
import com.common.util.DateHelper;
import com.common.util.PagerModel;
import com.workflow.bean.Outputdept;
import com.workflow.service.OutputdeptService;

public class OutputdeptServiceImpl extends AbstractManager implements
		OutputdeptService {

	public void addOutputdept(Outputdept outputdept) {
		StringBuilder outputno = new StringBuilder();//32位以内
		Long count = 0L;
		String hql = "select count(*) from Outputdept";//数量统计6位
		count = (Long) this.getHibernateTemplate().find(hql).get(0);
		count %= 1000L;
		
		Long num = Long.parseLong(DateHelper.dateToStr(new Date(), "yyyyMMddHms"));//13位
		num *= 1000L;//long 数据范围		
		num += count;
		
		String deptcode = outputdept.getDepartmentByDeptcode().getDeptcode();
		outputno.append(deptcode.substring(0, deptcode.length()>6?6:deptcode.length()));//最好有个简称且不超过6位
		outputno.append("-CK-");
		outputno.append(num);
		
		outputdept.setOutputno(outputno.toString());
		outputdept.setStartdate(new Date());
		
		this.getHibernateTemplate().save(outputdept);
	}

	@SuppressWarnings("unchecked")
	public List<Outputdept> findAllOutputdept() {
		String hql = "from Outputdept op order by op.departmentByDeptcode.deptcode, op.outputno";
		return this.getHibernateTemplate().find(hql);
	}

	public Outputdept findOutputdept(String outputno) {
		return (Outputdept) this.getHibernateTemplate().load(Outputdept.class, outputno);
	}

	public PagerModel findOutputdeptForPager() {
		String hql = "from Outputdept op order by op.departmentByDeptcode.deptcode, op.outputno";
		return searchPaginated(hql);
	}

	public PagerModel findOutputdeptForPager(String deptcode) {
		if(deptcode == "") {
			return findOutputdeptForPager();
		}
		
		String hql = "from Outputdept op where op.departmentByDeptcode.deptcode = ? order by op.outputno";
		return searchPaginated(hql,deptcode);
	}

	public void removeOutputdept(String outputno) {
		String hql = "from Outputdeptdetail opd where opd.outputdept.outputno = ?";
		List list = this.getHibernateTemplate().find(hql,outputno);
		
		if(list == null || list.size() == 0	) {
			Outputdept outputdept = (Outputdept) this.getHibernateTemplate().load(Outputdept.class, outputno);
			if(outputdept != null) {
				this.getHibernateTemplate().delete(outputdept);
			}
		}else {
			throw new RuntimeException("you shall remove the items of Outputdeptdetail before with Outputdept outputno:"+outputno);
		}
	}

	public void updateOutputdept(Outputdept outputdept) {
		this.getHibernateTemplate().update(outputdept);
	}

}
